package hr.fer.zemris.revhttp.gateway.websockets;

import hr.fer.zemris.revhttp.gateway.resources.GatewayResources;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.eclipse.jetty.util.ajax.JSON;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketServlet;

/**
 * @author tomek
 */
public class ServerInterfaceServlet extends WebSocketServlet {

	private static final long serialVersionUID = 1L;

	private Set<WebSocket> connections = new HashSet<WebSocket>();

	@Override
	protected WebSocket doWebSocketConnect(HttpServletRequest request,
			String protocol) {
		return new ServerInterfaceSocket();
	}

	public class ServerInterfaceSocket implements WebSocket {

		private Outbound outbound;

		@Override
		public void onConnect(Outbound outbound) {
			this.outbound = outbound;
			connections.add(this);
		}

		@Override
		public void onDisconnect() {
			connections.remove(this);
		}

		@Override
		public void onMessage(byte frame, String data) {

			System.out.println("neko je poslal: " + data);
			Object responseObj = RequestHandler.parseRequest(
					JSON.parse(data), this);
			if (responseObj != null)
				try {
					String response = JSON.toString(responseObj);
					outbound.sendMessage(frame, response);
					System.out.println("vratil sam mu: " + response);
				} catch (IOException e) {
					e.printStackTrace();
				}
		}

		@Override
		public void onMessage(byte frame, byte[] data, int offset,
				int length) {
		}

		public void relayRequest(String requestId, String contextPath) {
			try {
				outbound.sendMessage((byte) 0, JSON.toString(JSON
						.parse("{\"revhttp\" : {\"Method\" : \"REQUEST\",  \"registrationKey\" : \" " +  GatewayResources.getResourceUUID(contextPath) + " \", \"pathRegex\": \""
								+ contextPath
								+ "\", \"requestId\" : \"" + requestId + "\", \"realPrefix\" : \"localhost:8080/apps\"}}")));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
